package com.reliable.service.serviceimpl;

import com.reliable.common.annotation.DataSource;
import com.reliable.common.enums.DataSourceType;
import com.reliable.service.domain.UploadSessionRef;
import com.reliable.service.mapper.UploadSessionRefMapper;
import com.reliable.service.service.IUploadSessionRefService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Qualifier;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Date;

/**
 * 上传会话关联Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-17
 */
@Service
@DataSource(value = DataSourceType.PG)
public class UploadSessionRefServiceImpl extends ServiceImpl<UploadSessionRefMapper, UploadSessionRef> implements IUploadSessionRefService {
    
    @Autowired
    private UploadSessionRefMapper uploadSessionRefMapper;

    @Autowired
    private javax.sql.DataSource dataSource;

    @Autowired
    @Qualifier("pgJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    /**
     * 批量插入上传会话关联记录
     * 参考 ChatMessageServiceImpl.batchInsertChatMessages 方法实现
     * 
     * @param uploadId 上传记录ID
     * @param sessionIds 会话ID列表
     * @throws SQLException SQL异常
     */
    public void batchInsertSessionRefs(Long uploadId, List<String> sessionIds) throws SQLException {
        if (sessionIds == null || sessionIds.isEmpty()) {
            return;
        }

        String sql = "INSERT INTO upload_session_ref (upload_id, session_id) VALUES (?, ?)";
        
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            conn.setAutoCommit(false);
            
            for (String sessionId : sessionIds) {
                ps.setLong(1, uploadId);
                ps.setString(2, sessionId);
                ps.addBatch();
            }
            
            ps.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            throw new SQLException("批量插入上传会话关联记录失败: " + e.getMessage(), e);
        }
    }
}